<template>
  <div class="bazijp-pay">
    <div class="bazijp-pay__header">
      <h2>{{ selectTimeInfo.userName }}的八字精批</h2>
      <p style="font-size: 12px">
        欠缺信息：<b>原局缺水</b><br /><b
          >农历 {{ currentMonth }} 月或
          {{
            currentMonth < 11
              ? currentMonth + 2
              : currentMonth == 11
              ? "1"
              : "2"
          }}月有危机</b
        ><br />
        先天格局：<b>劫财有争夺 运势波动大可借贵人运势</b><br /><b>2025 年</b
        >，九紫离火运最利你的突破契机在今..
      </p>
    </div>
    <div class="bazijp-pay__contents">
      <div class="bazijp-pay__basic-info">
        <div class="three-part">
          <div class="three-part__heading">
            <img src="../../assets/pic//basic_top.png" width="100%" /><!---->
          </div>
          <div
            class="three-part__content"
            style="
              background-image: url('https://hpay.yqiaoart.top/assets/basic_center.png');
              background-repeat: no-repeat; /* 防止重复 */
            "
          >
            <div class="bazijp-pay__basic-info-container">
              <dl>
                <dt>姓名：</dt>
                <dd>{{ selectTimeInfo.userName }}</dd>
                <dt>性别：</dt>
                <dd>{{ selectTimeInfo.sex == "1" ? "男" : "女" }}</dd>
                <dt>生辰：</dt>
                <dd class="colspan2">
                  {{ yingliInfo ? yingliInfo : yangliInfo
                  }}<!---->
                </dd>
                <!-- <dd class="colspan2">
                  {{ yingliType ? yingliInfo : yangliInfo }}
                </dd> -->
              </dl>
              <div class="adv">
                <img src="../../assets/pic//adv.png" />
              </div>
              <div class="price">
                限时特惠：<strong>{{ priceNum }}</strong>
                <del>原价：¥199</del>
              </div>
              <div class="bazijp-pay__countdown">
                <div class="countdown">
                  优惠倒计时
                  <span class="time" id="minutes">{{ minutes }}</span
                  ><dfn>:</dfn
                  ><span class="time" id="seconds">{{ seconds }}</span
                  ><dfn>:</dfn
                  ><span class="time" id="milliseconds">{{
                    milliseconds
                  }}</span>
                </div>
              </div>
              <!-- <div
                class="pay-channels"
                @click="goToPay"
                style="margin-bottom: 10px"
              >
                <a class="weixin"
                  ><img width="100%" src="../../assets/pic//weixin_dark.png" />
                  微信支付
                </a>
              </div> -->
              <div class="pay-channels" @click="goToZhiFuBaoPay">
                <a class="alipay"
                  ><img width="100%" src="../../assets/pic/alipay_dark.png" />
                  支付宝支付
                </a>
              </div>
            </div>
          </div>
          <img src="../../assets/pic//basic_bottom.png" width="100%" />
        </div>
      </div>
      <div class="lock">
        <img src="../../assets/pic//lock_1.png" /><img
          src="../../assets/pic//lock_2.png"
        /><img src="../../assets/pic//lock_3.png" /><img
          src="../../assets/pic//lock_4.png"
        /><img src="../../assets/pic//lock_5.png" /><img
          src="../../assets/pic//lock_6.png"
        /><img src="../../assets/pic//lock_7.png" />
      </div>
    </div>
  </div>
</template>
<script setup>
import router from "@/router";
import { useRoute } from "vue-router";
import { ref, computed, onMounted, onUnmounted, nextTick } from "vue";
import calendar from "js-calendar-converter";
import axios from "axios";
const route = useRoute(); // 获取当前路由信息

const minutes = ref(30);
const seconds = ref(0);
const milliseconds = ref(0);
const isRunning = ref(false);
const timerInterval = ref(null);
// 计算总毫秒数
const totalMilliseconds = computed(() => {
  return minutes.value * 60000 + seconds.value * 1000 + milliseconds.value;
});

const currentMonth = ref(10);

// 格式化数字为两位数
const formatNumber = (num) => {
  return num.toString().padStart(2, "0");
};

// 更新计时器显示
const updateDisplay = () => {
  const minutesDisplay = document.getElementById("minutes");
  const secondsDisplay = document.getElementById("seconds");
  const millisecondsDisplay = document.getElementById("milliseconds");

  minutesDisplay.textContent = formatNumber(minutes.value);
  secondsDisplay.textContent = formatNumber(seconds.value);
  millisecondsDisplay.textContent = formatNumber(milliseconds.value);

  // 添加数字变化动画
  minutesDisplay.classList.add("scale-110");
  secondsDisplay.classList.add("scale-110");
  millisecondsDisplay.classList.add("scale-110");

  setTimeout(() => {
    minutesDisplay.classList.remove("scale-110");
    secondsDisplay.classList.remove("scale-110");
    millisecondsDisplay.classList.remove("scale-110");
  }, 100);
};

// 开始计时器
const startTimer = () => {
  if (isRunning.value) return;
  if (totalMilliseconds.value <= 0) return;

  isRunning.value = true;
  timerInterval.value = setInterval(() => {
    if (milliseconds.value > 0) {
      milliseconds.value--;
    } else {
      if (seconds.value > 0) {
        seconds.value--;
        milliseconds.value = 99;
      } else {
        if (minutes.value > 0) {
          minutes.value--;
          seconds.value = 59;
          milliseconds.value = 99;
        } else {
          // 计时结束
          clearInterval(timerInterval.value);
          isRunning.value = false;
          timerComplete();
        }
      }
    }

    updateDisplay();
  }, 10); // 每 10 毫秒更新一次
};

const userIP = ref("");
const get_client_ip = () => {
  // const userIP = "";
  fetch("/api/client/getClientIp")
    .then((response) => response.json())
    .then((data) => {
      userIP.value = data.data; // 获取用户 IP userIP = data.ip; // 假设返回的数据中有 ip 字段
      // 然后将 userIP 作为参数传递
    });
  // return userIP;
};

const goToPay = () => {
  const info = JSON.parse(localStorage.getItem("submitFormInfo"));
  const dateObj = JSON.parse(info.time);

  // 将年月日格式化为 ****.**.**
  const formattedDate = `${dateObj.year}-${String(dateObj.month).padStart(
    2,
    "0"
  )}-${String(dateObj.day).padStart(2, "0")}`;
  let time = null;
  if (dateObj.hour.periodName == "时辰未知") {
    time = null;
  } else {
    time = `${String(dateObj.hour.startTime).padStart(2, "0")}-${String(
      dateObj.hour.endTime
    ).padStart(2, "0")}`;
  }
  const lcalendarSelect = localStorage.getItem("lcalendarSelect");
  const data = {
    birthDate: formattedDate,
    birthType: lcalendarSelect,
    timeRange: time,
    userName: info.userName,
    userSex: info.sex == 1 ? "男" : "女",
    phoneNumber: "",
  };

  axios.post("/api/order/add", data).then((res) => {
    // console.log(res);
    const useData = {
      total: priceNum.value * 100,
      // notifyUrl: "https://hpay.yqiaoart.top/basic-api/api/client/getClientIp",
      notifyUrl: "https://hpay.yqiaoart.top/basic-api/api/H5pay/notify",
      orderNum: res.data.data,
      clientIp: userIP.value || localStorage.getItem("userIP"),
    };
    localStorage.setItem("orderId", res.data.data);
    fetch("/api/H5pay/wechat", {
      method: "POST",
      body: JSON.stringify(useData),
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((response) => response.json())
      .then((data) => {
        const redirect_url = "https://hpay.yqiaoart.top/#/makesure";
        let encoded_url = encodeURIComponent(redirect_url);
        const h5Url = data.data.concat(
          "&" + "redirect_url=" + `${encoded_url}`
        );
        localStorage.setItem("havePayId", "true");
        window.location.href = h5Url; // 跳转到支付页面
      });
  });
  // })
  // .catch((error) => {
  //   console.error("获取 IP 地址失败：", error);
  // });

  // router.push("/afterPay");
};

const goToZhiFuBaoPay = () => {
  const info = JSON.parse(localStorage.getItem("submitFormInfo"));
  const dateObj = JSON.parse(info.time);

  // 将年月日格式化为 ****.**.**
  const formattedDate = `${dateObj.year}-${String(dateObj.month).padStart(
    2,
    "0"
  )}-${String(dateObj.day).padStart(2, "0")}`;
  let time = null;
  if (dateObj.hour.periodName == "时辰未知") {
    time = null;
  } else {
    time = `${String(dateObj.hour.startTime).padStart(2, "0")}-${String(
      dateObj.hour.endTime
    ).padStart(2, "0")}`;
  }
  const lcalendarSelect = localStorage.getItem("lcalendarSelect");
  const data = {
    birthDate: formattedDate,
    birthType: lcalendarSelect,
    timeRange: time,
    userName: info.userName,
    userSex: info.sex == 1 ? "男" : "女",
    phoneNumber: "",
  };

  axios.post("/api/order/add", data).then((res) => {
    // console.log(res);
    const useData = {
      total: priceNum.value,
      orderNum: res.data.data,
    };
    localStorage.setItem("orderId", res.data.data);
    fetch("/api/H5pay/zfb", {
      method: "POST",
      body: JSON.stringify(useData),
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((response) => response.json())
      .then((data) => {
        // const redirect_url = "https://hpay.yqiaoart.top/#/makesure";
        // let encoded_url = encodeURIComponent(redirect_url);
        const h5Url = data.data;
        localStorage.setItem("havePayId", "true");
        window.location.href = h5Url; // 跳转到支付页面
      });
  });
  // })
  // .catch((error) => {
  //   console.error("获取 IP 地址失败：", error);
  // });

  // router.push("/afterPay");
};

// 计时完成
const timerComplete = () => {
  // 添加完成动画
  const timerDisplay = document.querySelectorAll(".timer-display");
  timerDisplay.forEach((el) => {
    el.classList.add("text-danger");
    el.classList.add("animate-pulse");
  });

  // 播放提示音
  const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
  const oscillator = audioCtx.createOscillator();
  const gainNode = audioCtx.createGain();

  oscillator.connect(gainNode);
  gainNode.connect(audioCtx.destination);

  oscillator.type = "sine";
  oscillator.frequency.setValueAtTime(440, audioCtx.currentTime); // 440 Hz (A4)
  oscillator.frequency.exponentialRampToValueAtTime(
    880,
    audioCtx.currentTime + 0.5
  ); // 升至 880 Hz (A5)

  gainNode.gain.setValueAtTime(0, audioCtx.currentTime);
  gainNode.gain.linearRampToValueAtTime(0.5, audioCtx.currentTime + 0.1);
  gainNode.gain.linearRampToValueAtTime(0, audioCtx.currentTime + 0.6);

  oscillator.start();
  oscillator.stop(audioCtx.currentTime + 0.6);

  // 5 秒后恢复正常显示
  setTimeout(() => {
    timerDisplay.forEach((el) => {
      el.classList.remove("text-danger");
      el.classList.remove("animate-pulse");
    });
  }, 5000);
};
startTimer();
// 确认支付弹窗

const yingliType = ref("1");
// 生命周期钩子
onMounted(async () => {
  const currentDate = new Date();
  currentMonth.value = currentDate.getMonth() + 1;
  updateDisplay();
  getPrice();
  get_client_ip();
  const query = route.query;
  let info = "";
  if (localStorage.getItem("submitFormInfo")) {
    info = JSON.parse(localStorage.getItem("submitFormInfo"));
  }

  const data = localStorage.getItem("lcalendarSelect")
    ? localStorage.getItem("lcalendarSelect")
    : "";
  selectTimeInfo.value = info;
  yingliType.value = data;
  selectTimeInfo.value.time = JSON.parse(info.time);
});

const selectTimeInfo = ref({});

// 农历转公历
const convertDate = (year, month, day) => {
  try {
    // 示例：农历转公历
    const solarDate = calendar.lunar2solar(year, month, day);
    // 创建公历 Date 对象
    const resultDate = {
      year: solarDate.cYear,
      month: solarDate.cMonth, // 注意：JavaScript 月份是 0-11
      day: solarDate.cDay,
    };
    return resultDate;
  } catch (error) {
    console.log("日期转换失败：", error);
    return null;
  }
};

const priceNum = ref(38.8);
const getPrice = () => {
  axios.get("/api/paymentCount/get").then((res) => {
    priceNum.value = res.data.data;
  });
};

const yangliInfo = computed(() => {
  if (selectTimeInfo.value.time != null) {
    return (
      "阳历" +
      selectTimeInfo.value.time.year +
      "年" +
      selectTimeInfo.value.time.month +
      "月" +
      selectTimeInfo.value.time.day +
      "日"
    );
  }
  return "";
});
const monthsNongLi = [
  "正月",
  "二月",
  "三月",
  "四月",
  "五月",
  "六月",
  "七月",
  "八月",
  "九月",
  "十月",
  "十一月",
  "十二月",
];
const digits = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
const lunarDayNames = [
  "初一",
  "初二",
  "初三",
  "初四",
  "初五",
  "初六",
  "初七",
  "初八",
  "初九",
  "初十",
  "十一",
  "十二",
  "十三",
  "十四",
  "十五",
  "十六",
  "十七",
  "十八",
  "十九",
  "二十",
  "廿一",
  "廿二",
  "廿三",
  "廿四",
  "廿五",
  "廿六",
  "廿七",
  "廿八",
  "廿九",
];
const yingliInfo = computed(() => {
  if (selectTimeInfo.value.time == null || yingliType.value == "0") {
    return "";
  }
  if (yingliType.value == "0") {
    // 公历转农历
    let nongli = calendar.solar2lunar(
      selectTimeInfo.value.time.year,
      selectTimeInfo.value.time.month,
      selectTimeInfo.value.time.day
    );
    // console.log(nongli)lYear
    return `阴历：${numberToChineseDigits(nongli.lYear)}年${
      monthsNongLi[nongli.lMonth - 1]
    }${nongli.IDayCn}日`;
  } else {
    return `阴历：${numberToChineseDigits(selectTimeInfo.value.time.year)}年${
      monthsNongLi[selectTimeInfo.value.time.month - 1]
    }${
      selectTimeInfo.value.time.day == 30
        ? "三十"
        : lunarDayNames[selectTimeInfo.value.time.day - 1]
    }`;
  }
});

/**
 * 将阿拉伯数字逐位转换为中文数字表示
 * @param {number|string} num - 需要转换的数字
 * @returns {string} 转换后的中文数字字符串
 */
const numberToChineseDigits = (num) => {
  // 检查输入是否有效
  if (typeof num !== "number" && typeof num !== "string") {
    return "";
  }

  // 将输入转换为字符串
  const numStr = String(num).replace(/[^\d]/g, ""); // 移除非数字字符

  if (!numStr) {
    return "";
  }

  // 中文数字映射
  const chineseDigits = [
    "零",
    "一",
    "二",
    "三",
    "四",
    "五",
    "六",
    "七",
    "八",
    "九",
  ];

  // 逐位转换
  let result = "";
  for (let i = 0; i < numStr.length; i++) {
    const digit = parseInt(numStr[i]);
    result += chineseDigits[digit];
  }

  return result;
};
onUnmounted(() => {
  if (timerInterval.value) {
    clearInterval(timerInterval.value);
  }
});
</script>

<style scoped>
@import url("../../assets/index_static/app.css");
</style>
